import urllib,urllib2,re,sys,xbmcplugin,xbmcgui
import cookielib,os,string,cookielib,StringIO
import os,time,base64,logging
import xbmcaddon
try:
    import json
except ImportError:
    import simplejson as json

fpt=xbmcaddon.Addon(id='plugin.video.fptv3')
pluginhandle = int(sys.argv[1])
user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:10.0a1) Gecko/20111029 Firefox/10.0a1'

def ShowMess(type):
    if type == 'fileremo':
        xbmc.executebuiltin("XBMC.Notification('Fast Pass TV',This file has been removed!,4000)")
    elif type == 'favadded':
        xbmc.executebuiltin("XBMC.Notification('Fast Pass TV',Added to favourites!,3000)")
    elif type == 'favremo':
        xbmc.executebuiltin("XBMC.Notification('Fast Pass TV',Removed from favourites!,3000)")

def geturl(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', user_agent)
    response = urllib2.urlopen(req)
    link=response.read()
    response.close()
    return link

def redirect(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', user_agent)
    response = urllib2.urlopen(req)
    gurl=response.geturl()
    response.close()
    return gurl

def xbmcpath(path,filename):
    translatedpath = os.path.join(xbmc.translatePath( path ), ''+filename+'')
    return translatedpath

def openfile(filename):
    fh = open(filename, 'r')
    contents=fh.read()
    fh.close()
    return contents

def save(filename,contents):
    fh = open(filename, 'w')
    fh.write(contents)
    fh.close()

#Paths
fptpath = 'special://temp/'
fptdatapath = 'special://profile/addon_data/plugin.video.FastpassTV'
translatedfptpath = xbmcpath(fptpath,'')
parentpath = xbmcpath(fptdatapath,'')
path = fpt.getAddonInfo('path')
artPath=path+'\\resources\\art'

# Cache files
referer = xbmcpath(fptdatapath,'ref.txt')
movPage = xbmcpath(fptdatapath,'mov.txt')
epPage = xbmcpath(fptdatapath,'ep.txt')
tvPage = xbmcpath(fptdatapath,'tv.txt')
docPage = xbmcpath(fptdatapath,'doc.txt')
toonPage = xbmcpath(fptdatapath,'toon.txt')

# Art & favourites
favPath=xbmcpath(fptdatapath,'favtv')
favPath2=xbmcpath(fptdatapath,'favmov')
movIcon = artPath+'\\movie.png'
tvIcon = artPath+'\\tv.png'

def StartupStuff():
    if not os.path.exists(parentpath):
        os.makedirs(parentpath)
    read = open(favPath, 'a+')
    read.close()
    read = open(favPath2, 'a+')
    read.close()

def CATS():
    StartupStuff()
    addDir('Favourites','http://www.fastpasstv.ms/',31,artPath+'\\fav.png')
    addDir('Most Popular Today','http://www.fastpasstv.ms/',32,artPath+'\\pop.png')
    addDir('Recently Added','http://www.fastpasstv.ms/tv/',33,artPath+'\\recent.png')
    addDir('TV Shows','http://www.fastpasstv.ms/tv',2,tvIcon)
    addDir('Movies','http://www.fastpasstv.ms/movies',1,movIcon)
    addDir('Documentaries','http://www.fastpasstv.ms/documentaries',14,artPath+'\\doc.png')
    addDir('Cartoons','http://www.fastpasstv.ms/cartoons',38,artPath+'\\cartoon.png')
    addDir('Search','http://www.fastpasstv.ms/',4,artPath+'\\find.png')

def POPULAR(url):
    link= geturl(url)
    mvs=re.compile('<li><a href="/movies/(.+?)">(.+?)</a></li>').findall(link)
    tvs=re.compile('<li><a href="/tv/(.+?)">(.+?)</a></li>').findall(link)
    for url2,name in tvs:
        addDir(name,'http://www.fastpasstv.ms/tv/'+url2,9,tvIcon)
    for url2,name in mvs:
        addDir(name,'http://www.fastpasstv.ms/movies/'+url2,9,movIcon)

def RECENT():
    addDir('Latest TV Shows','http://www.fastpasstv.ms/tv/',11,tvIcon)
    addDir('Latest Movies','http://www.fastpasstv.ms/movies',11,movIcon)
    addDir('Latest Documentaries','http://www.fastpasstv.ms/documentaries',11,artPath+'\\doc.png')
    addDir('Latest Cartoons','http://www.fastpasstv.ms/cartoons',11,artPath+'\\cartoon.png')

def LATEST(url,name):
    link= geturl(url)
    all = re.compile('<b>Latest additions</b>.+?<ul class="pagination">', re.DOTALL).findall(link)
    doc = re.compile('<a href="(.+?)">(.+?)</a>').findall(all[0])
    for url,name in doc:
        addDir(name.replace('&amp;','&'),'http://www.fastpasstv.ms'+url,9,'')
        
def FAVS():
    addDir('TV Shows','http://www.fastpasstv.ms/',20,tvIcon)
    addDir('Features','http://www.fastpasstv.ms/',30,movIcon)

def FAVTV():
    read = open(favPath, 'r')
    text = read.read()
    favs=re.compile('"(.+?)\|(.+?)"').findall(text)
    favs.sort()
    read.close()
    for name,url in favs:
        addDir(name,url,10,tvIcon)
        
def FAVMOV():
    i=0
    read = open(favPath2, 'r')
    text = read.read()
    favs=re.compile('"(.+?)\|(.+?)"').findall(text)
    favs.sort()
    read.close()
    for name,url in favs:
        i=i+1
        addDir(name,url,9,movIcon)

def ADDFAVS(url,name):
    mu = '/tv/'
    mu2 = '/movies/'
    if mu in url:
        read = open(favPath, 'a+')
    elif mu2 in url:
        read = open(favPath2, 'a+')
    else:return
    read.write('"'+url+'\n')
    ShowMess('favadded')
    read.close()
    
def REMFAVS(url,name):
    mu = '/tv/'
    mu2 = '/movies/'
    murl=re.compile('\|(.+?)"').findall(url)
    ShowMess('favremo')
    if mu in url:
        read = open(favPath, 'r')
    elif mu2 in url:
        read = open(favPath2, 'r')
    else:return
    lines = read.readlines()
    read.close()
    if mu in url:
       read = open(favPath, 'w')
    elif mu2 in url:
       read = open(favPath2, 'w')
    else:return
    for line in lines:
        if not murl[0] in line:
            read.write(line)
    read.close()

def MAIN(url,name):
	i=0
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:10.0a1) Gecko/20111029 Firefox/10.0a1')
        response2 = urllib2.urlopen(req)
        ref=response2.geturl()
	save(referer,ref)
        link=response2.read()
#   mega=re.compile('<b>Megavid.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	putloc=re.compile('<b>Put.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"', re.IGNORECASE).findall(link)
	vidbx3=re.compile('<b>Vidbu.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	nova=re.compile('<b>Novamo.+?</b></td>\W*<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	divxavi=re.compile('<b>Divxden.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	divxflash=re.compile('<b>Divxden</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
#	dv=re.compile('<b>Vidxden.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	dvflash=re.compile('<b>Vidxden.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	vidweed=re.compile('<b>Videow.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	vidbb=re.compile('<b>Videob.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	movsh=re.compile('<b>Movsh.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	socksh=re.compile('<b>Socks.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	divxst=re.compile('<b>Divxstage.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	royal=re.compile('<b>Royal.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	motion=re.compile('<b>Dailymot.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
	google=re.compile('<b>Video.goo.+?</b></td>\n.+?<td class="siteparts" style="width:.+?px;"><a class="link"[^>]+?href="(.+?)"').findall(link)
#	for url in dv:
#		i=i+1
#		addDir(str(i)+'. Vidxden','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),15,'')
	for url in dvflash:
		i=i+1
		addDir(str(i)+'. Vidxden(flv)','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),28,'')
	for url in divxavi:
		i=i+1
		addDir(str(i)+'. Divxden','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),15,'')
#	for url in mega:
#		i=i+1
#		addDir(str(i)+'. Megavideo','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),8,'')
	for url in putloc:
		i=i+1
		addDir(str(i)+'. Putlocker','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),12,'')
	for url in nova:
		i=i+1
		addDir(str(i)+'. Novamov','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),6,'')
	for url in movsh:
		i=i+1
		addDir(str(i)+'. Movshare','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),19,'')
	for url in socksh:
		i=i+1
		addDir(str(i)+'. Sockshare','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),23,'')
	for url in divxst:
		i=i+1
		addDir(str(i)+'. Divxstage.eu','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),24,'')
	for url in royal:
		i=i+1
		addDir(str(i)+'. Royalvids.eu','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),25,'')
	for url in motion:
		i=i+1
		addDir(str(i)+'. DailyMotion','http://www.fastpasstv.ms'+url.replace('/watch','/redirect'),26,'')

def MOVALL(url,name):
    cache=fpt.getSetting('cache_time')
    cache=int(cache)
    try:
        tooOld=time.time() - os.path.getmtime(movPage) > ( cache * 60)
    except:
        tooOld=True
    if tooOld == True or cache == '0':
        link= geturl(url)
        save(movPage,link)
    else:
        link=openfile(movPage)
    sec=re.compile('<h3 id="(.+?)">').findall(link)
    for sect in sec:
        addDir(sect,'http://www.fastpasstv.ms/movies',36,artPath+'\\'+sect+'.png')
		
def MOVALPH(url,name):
    movlist=openfile(movPage)
    mvs=re.compile('<li[^>]+?><a[^>]+?href="(.+?)">(.+?)<span class="epnum">(.+?)</span></a></li>').findall(movlist)
    for url,title,year in mvs:
	    turl=name.lower()
	    if name == '0-9':
	        if re.search('/movies/[0-9]|/movies/the-[0-9]',url) != None:
	            addDir(title.replace('<font class="newvid">New!</font>','([COLOR=red]NEW[/COLOR])')+' ('+year+')','http://www.fastpasstv.ms'+url,9,movIcon)
	    elif turl == 't':
	        if re.search('/movies/the-t|/movies/t',url) != None and re.search('/movies/the-[a-s-u-z-0-9_]',url) == None:
	            addDir(title.replace('<font class="newvid">New!</font>','([COLOR=red]NEW[/COLOR])')+' ('+year+')','http://www.fastpasstv.ms'+url,9,movIcon)
	    elif url.find('/movies/'+turl) != -1 or url.find('/movies/the-'+turl) != -1:
	        addDir(title.replace('<font class="newvid">New!</font>','([COLOR=red]NEW[/COLOR])')+' ('+year+')','http://www.fastpasstv.ms'+url,9,movIcon)
	        
def TVALL(url,name):
    cache=fpt.getSetting('cache_time')
    cache=int(cache)
    try:
        tooOld=time.time() - os.path.getmtime(tvPage) > ( cache * 60)
    except:
        tooOld=True
    if tooOld == True or cache == '0':
        link=geturl(url)
        save(tvPage,link)
    else:
        link=openfile(tvPage)
    sec=re.compile('<h3 id="(.+?)">').findall(link)
    for sect in sec:
        addDir(sect,'http://www.fastpasstv.ms/tv',37,artPath+'\\'+sect+'.png')

def TVALPH(url,name):
    tvlist=openfile(tvPage)
    tvs=re.compile('<li><a title=".+?" href="(.+?)">(.+?)<span class="epnum">(.+?)</span></a></li>').findall(tvlist)
    for url,title,eps in tvs:
        turl=name.lower()
        if name == '0-9':
            if re.search('/tv/[0-9]|/tv/the-[0-9]',url) != None:
                addDir(title.replace('<font class="newvid">New Episodes!</font>','([COLOR=red]NEW EPISODE[/COLOR])')+' ('+eps+')','http://www.fastpasstv.ms'+url,10,tvIcon)
        elif turl == 't':
            if re.search('/movies/the-t|/tv/t',url) != None and re.search('/tv/the-[a-s-u-z-0-9_]',url) == None:
                addDir(title.replace('<font class="newvid">New Episodes!</font>','([COLOR=red]NEW EPISODE[/COLOR])')+' ('+eps+')','http://www.fastpasstv.ms'+url,10,tvIcon)
        elif url.find('/tv/'+turl) != -1 or url.find('/tv/the-'+turl) != -1:
            addDir(title.replace('<font class="newvid">New Episodes!</font>','([COLOR=red]NEW EPISODE[/COLOR])')+' ('+eps+')','http://www.fastpasstv.ms'+url,10,tvIcon)

def TVSHOWS(url,name):
    link= geturl(url)
    save(epPage,link)
    try:
        read = open(favPath, 'r')
    except IOError:
        read = open(favPath, 'a+')
    lines = read.readlines()
    read.close()
    blah=re.sub(' \(.+?\)', '', name, re.DOTALL)
    seas=re.compile('<h3>Season (.+?)</h3>').findall(link)
    for sea in seas:
	    addDir('Season '+sea,url,35,tvIcon)

def TVEPS(url,name):
    tvlist=openfile(epPage)
    seas=re.compile('Season (.+)').findall(name)[0]
    tvs=re.compile('<li class="episode"><a href="/tv/(.+?)/season-(.+?)/(.+?)">(.+?)</a></li>').findall(tvlist)
    for title,sea,url,name in tvs:
        if sea == seas:
            addDir('S'+sea+'E'+name,'http://www.fastpasstv.ms/tv/'+title+'/season-'+sea+'/'+url,9,tvIcon)

def DOCALL(url,name):
    cache=fpt.getSetting('cache_time')
    cache=int(cache)
    try:
        tooOld=time.time() - os.path.getmtime(docPage) > ( cache * 60)
    except:
        tooOld=True
    if tooOld == True or cache == '0':
        link=geturl(url)
        save(docPage,link)
    else:
        link=openfile(docPage)
    doc=re.compile('<li><a href="(.+?)">(.+?)<span class="epnum">(.+?)</span></a></li>').findall(link)
    for url,name,year in doc:
        addDir(name.replace('<font class="newvid">New!</font>','([COLOR=red]NEW[/COLOR]')+' ('+year+')','http://www.fastpasstv.ms'+url,9,artPath+'\\doc.png')

def TOONALL(url,name):
    cache=fpt.getSetting('cache_time')
    cache=int(cache)
    try:
        tooOld=time.time() - os.path.getmtime(toonPage) > ( cache * 60)
    except:
        tooOld=True
    if tooOld == True or cache == '0':
        link=geturl(url)
        save(toonPage,link)
    else:
        link=openfile(toonPage)
    toon=re.compile('<li><a href="(.+?)">(.+?)<span class="epnum">(.+?)</span></a></li>').findall(link)
    for url,name,year in toon:
        addDir(name.replace('<font class="newvid">New!</font>','([COLOR=red]NEW[/COLOR]')+' ('+year+')','http://www.fastpasstv.ms'+url,9,artPath+'\\cartoon.png')

# Start Sources
def SOCKSH(url,name):
    link1 = geturl(url)
    link2 = redirect(url)
    try:
        hash=re.compile('type="hidden" value="(.+?)" name="hash"').findall(link1)[0]
    except:
        ShowMess('fileremo')
        return
    values = {'hash': hash, 'confirm':'Continue as Free User'}
    headers = { 'User-Agent' : user_agent}
    cookiejar = cookielib.LWPCookieJar()
    cookiejar = urllib2.HTTPCookieProcessor(cookiejar)
    opener = urllib2.build_opener(cookiejar)
    urllib2.install_opener(opener)
    data = urllib.urlencode(values)
    req = urllib2.Request(link2, data, headers)
    response = urllib2.urlopen(req)
    link = response.read()
    response.close()
    code = re.compile("stream=(.+?)'").findall(link)
    req = urllib2.Request('http://www.sockshare.com/get_file.php?stream='+code[0])
    req.add_header('User-Agent', user_agent)
    response = urllib2.urlopen(req)
    link=response.read()
    response.close()
    finalurl = re.compile('<media:content url="(.+?)"').findall(link)[0]
    Play(finalurl)

def MOTION(url,name):
    link = geturl(url)
    seq=re.compile('"sequence",  "(.+?)"').findall(link)
    newseq = urllib.unquote(seq[0]).decode('utf8').replace('\\/','/')
    low=re.compile('"sdURL":"(.+?)"').findall(newseq)
    high=re.compile('"hqURL":"(.+?)"').findall(newseq)
    finalurl = ''
    if(len(high) == 0):
        finalurl = low[0]
    else:
        finalurl = high[0]
    Play(finalurl)

def MOVSHARE(url,name):
    link1= redirect(url)
    link=geturl(link1)
    link = ''.join(link.splitlines()).replace('\t','').replace('\'','"')
    try:
        text=re.compile('<h3>This file no longer exists on our servers.</h3>').findall(link)[0]
    except:pass
    else:
        ShowMess('fileremo')
        return
    if re.search('Video hosting is expensive. We need you to prove you"re human.',link):
        values = {'wm': '1'}
        headers = { 'User-Agent' : user_agent }
        data = urllib.urlencode(values)
        req = urllib2.Request(link1, data, headers)
        response = urllib2.urlopen(req)
        link=response.read()
        response.close()
        link = ''.join(link.splitlines()).replace('\t','').replace('\'','"')
    divx=re.compile('param name="src" value="(.+?)"').findall(link)
    if(len(divx) == 0):
        part1=re.compile('flashvars.file="(.+?)"').findall(link)[0]
        part2=re.compile('flashvars.filekey="(.+?)"').findall(link)[0]
        url2 = "http://www.movshare.net/api/player.api.php?user=undefined&codes=undefined&pass=undefined&file="+part1+"&key="+part2
        link=geturl(url2)
        finalurl=re.compile('url=(\S*)&title').findall(link)[0]
        Play(finalurl)
    else:
        Play(divx[0])
		
def VIDXFLV(url,name):
	link1 = geturl(url)
	link2 = redirect(url)
	try:
		fcodenm=re.compile('name="fname" type="hidden" value="(.+?)"').findall(link1)[0]
	except:
		dialog = xbmcgui.Dialog()
		ok = dialog.ok("FastPassTv",'The file has been removed due to copyright.')
		return

	fcodeid=re.compile('name="id" type="hidden" value="(.+?)"').findall(link1)[0]
	refer=openfile(referer)

	values = {'op': 'download1','usr_login': ' ','id': fcodeid, 'fname': fcodenm,'referer' : refer, 'method_free':'Continue to Video'}
	user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
	headers = { 'User-Agent' : user_agent }
	cookiejar = cookielib.LWPCookieJar()
	cookiejar = urllib2.HTTPCookieProcessor(cookiejar) 
	opener = urllib2.build_opener(cookiejar)
	urllib2.install_opener(opener)

	data = urllib.urlencode(values)
	req = urllib2.Request(link2, data, headers)
	response = urllib2.urlopen(req)
	link = response.read()

	file = re.compile("image(.+?)364|divxden").findall(link)[0]
	print file
	cleanup = file.replace('|',' ').replace('||',' ')
	hashlong = cleanup[-46:].replace(' ','')
	hashshort =  re.compile('divxden(.+?)file').findall(link)[0]
   	finalurl = 'http://'+hashshort.replace('the','').replace('you','').replace(' ','').replace('|','')+'.divxden.com:364/d/'+hashlong+'/'+ fcodenm
	Play(finalurl)
	
def GOOGLE(url,name):
    try:
        link=redirect(url)
    except:
        ShowMess('fileremo')
        return
    id=re.compile('http://video.google.com/videoplay\?docid=(.+)').findall(link)[0]
    link=geturl('http://video.google.com/docinfo?%7B%22docid%22:%22'+id+'%22%7D')
    finalurl = re.compile('"streamer_url":"(.+?)"').findall(link)[0].replace('\\u0026','&')
    Play(finalurl)

def VIDEOBB(url,name):
    link=redirect(url)
    ursplit=re.compile('v=(\w*)').findall(link)
    url2='http://www.videobb.com/player_control/settings.php?v='+ursplit[0]
    test=geturl(url2)
    try:
        text=re.compile('"text":"This video was either deleted by the user or in breach of a copyright holder."').findall(test)[0]
    except:pass
    else:
        ShowMess('fileremo')
        return
    settingsObj=json.load(urllib.urlopen(url2))['settings']
    imgUrl=str(settingsObj['config']['thumbnail'])
    finalurl=str(base64.b64decode(settingsObj['config']['token1']))
    Play(finalurl)
    
def DIVXSTAGE(url,name):
    link=geturl(url)
    part1=re.compile('flashvars.file="(.+?)"').findall(link)
    part2=re.compile('flashvars.filekey="(.+?)"').findall(link)
    if (len(part1) == 0):
        ShowMess('fileremo')
        return
    url2="http://www.divxstage.eu/api/player.api.php?user=undefined&codes=undefined&pass=undefined&file="+part1[0]+"&key="+part2[0]
    link=geturl(url2)
    finalurl=re.compile('url=(.+?)&').findall(link)[0]
    Play(finalurl)
    
def ROYAL(url,name):
    link= geturl(url)
    finalurl=re.compile('name="flashvars" value="file=(.+?)&').findall(link)
    if (len(finalurl) == 0):
        ShowMess('fileremo')
        return
    Play(finalurl[0])

def VIDEOWEED(url,name):
    link=geturl(url)
    part1=re.compile('flashvars.file="(.+?)"').findall(link)
    part2=re.compile('flashvars.filekey="(.+?)"').findall(link)
    if (len(part1) == 0):
        ShowMess('fileremo')
        return
    url2="http://www.videoweed.es/api/player.api.php?user=undefined&codes=undefined&pass=undefined&file="+part1[0]+"&key="+part2[0]
    link=geturl(url2)
    finalurl=re.compile('url=(.+?)&').findall(link)[0]
    Play(finalurl)

def PUTLOC(url,name):
    link1=geturl(url)
    link2=redirect(url)
    try:
        hash=re.compile('type="hidden" value="(.+?)" name="hash"').findall(link1)[0]
    except:
        ShowMess('fileremo')
        return
    values={'hash': hash, 'confirm':'Continue as Free User'}
    headers={ 'User-Agent' : user_agent}
    cookiejar=cookielib.LWPCookieJar()
    cookiejar=urllib2.HTTPCookieProcessor(cookiejar)
    opener=urllib2.build_opener(cookiejar)
    urllib2.install_opener(opener)
    data=urllib.urlencode(values)
    req=urllib2.Request(link2, data, headers)
    response=urllib2.urlopen(req)
    link=response.read()
    response.close()
    code=re.compile("stream=(.+?)'").findall(link)
    link=geturl('http://www.putlocker.com/get_file.php?stream='+code[0])
    finalurl=re.compile('<media:content url="(.+?)"').findall(link)[0]
    Play(finalurl)
        
def VIDXFLV(url,name):
	link1=geturl(url)
	link2=redirect(url)
	try:
		fcodenm=re.compile('name="fname" type="hidden" value="(.+?)"').findall(link1)[0]
	except:
	    ShowMess('fileremo')
	    return
	fcodeid=re.compile('name="id" type="hidden" value="(.+?)"').findall(link1)[0]
	refer=openfile(referer)
	values = {'op': 'download1','usr_login': ' ','id': fcodeid, 'fname': fcodenm,'referer' : refer, 'method_free':'Continue to Video'}
	headers = { 'User-Agent' : user_agent }
	cookiejar = cookielib.LWPCookieJar()
	cookiejar = urllib2.HTTPCookieProcessor(cookiejar) 
	opener = urllib2.build_opener(cookiejar)
	urllib2.install_opener(opener)
	data = urllib.urlencode(values)
	req = urllib2.Request(link2, data, headers)
	response = urllib2.urlopen(req)
	link = response.read()
	response.close()
	file = re.compile("image(.+?)364|divxden").findall(link)[0]
	cleanup = file.replace('|',' ').replace('||',' ')
	hashlong = cleanup[-46:].replace(' ','')
	hashshort =  re.compile('divxden(.+?)file').findall(link)[0]
   	finalurl = 'http://'+hashshort.replace('the','').replace('you','').replace(' ','').replace('|','')+'.divxden.com:364/d/'+hashlong+'/'+ fcodenm
	Play(finalurl)

def VIDBUX(url,name):
	link1=geturl(url)
	link2=redirect(url)
	try:
		fcodenm=re.compile('name="fname" type="hidden" value="(.+?)"').findall(link1)[0]
	except:
	    ShowMess('fileremo')
        return
	fcodeid=re.compile('name="id" type="hidden" value="(.+?)"').findall(link1)[0]
	refer=openfile(referer)
	values = {'op': 'download1','usr_login': ' ','id': fcodeid, 'fname': fcodenm,'referer' : refer, 'method_free':'Continue to Video'}
	headers = { 'User-Agent' : user_agent }
	data = urllib.urlencode(values)
	req = urllib2.Request(link2, data, headers)
	response = urllib2.urlopen(req)
	link = response.read()
	response.close()
	file=re.compile("vidbux(.+?)182|file").findall(link)[0]
	cleanup=file.replace('|',' ').replace('||',' ')
	hashlong = cleanup[-41:].replace(' ','')
	hashshort =  re.compile('</div><!-- <img src="http://(.+?).vidbux.com').findall(link)[0]
   	finalurl = 'http://'+hashshort+'.vidbux.com:182/d/'+hashlong+'/'+ fcodenm + '?start=0'
   	Play(finalurl)

def Nova(url,name):
    link=geturl(url)
    file=re.compile('flashvars.file="(.+?)"').findall(link)[0]
    filekey=re.compile('flashvars.filekey="(.+?)"').findall(link)[0]
    link=geturl('http://www.novamov.com/api/player.api.php?key='+ filekey + '&user=undefined&codes=1&file='+ file +'&pass=undefined')
    finalurl=re.compile('url=http://(.+?)&title=.+?').findall(link)[0]
    Play('http://'+finalurl)

#def MEGA(url,name):
#	gurl=redirect(url)
#	code=gurl[-8:]
#	try:
#	    req=urllib2.Request("http://www.megavideo.com/xml/videolink.php?v="+code)
#	    req.add_header('User-Agent', user_agent)
#	    req.add_header('Referer', 'http://www.megavideo.com/')
#	    lemon=urllib2.urlopen(req);response=lemon.read();lemon.close()
#	    errort=re.compile(' errortext="(.+?)"').findall(response)
#	    if len(errort) > 0: addLink(errort[0],'http://novid.com','')
#	    else:
#	        s = re.compile(' s="(.+?)"').findall(response)
#	        k1 = re.compile(' k1="(.+?)"').findall(response)
#	        k2 = re.compile(' k2="(.+?)"').findall(response)
#	        un = re.compile(' un="(.+?)"').findall(response)
#	        finalurl = "http://www" + s[0] + ".megavideo.com/files/" + __calculateFileHash(un[0], k1[0], k2[0]) + "/"
#	    Play(finalurl)
#	except:
#	    ShowMess('fileremo')
#	    return

def __calcDecriptionMix(hash, keyMix):
  """Mixes the decription keys into the hash and returns the updated hash
  @param hash: the hash to merge the keys into
  @param keyMix: the array of keys to mix"""
  for i in range(128):
    hash[i] = str(int(hash[i]) ^ int(keyMix[i + 256]) & 1)
  return "".join(hash)

def __toHexDecriptionString(binaryChunks):
  """Converts an array of binary strings into a string of the corresponding hex chunks merged
  This method will first loop through the binary strings converting each one into it's correspondent
  hexadecimal string and then merge the resulting array into a string
  @param binaryChunks: an array of binary strings
  @return: a string of the corresponding hexadecimal strings, merged"""
  hexChunks = []
  for binChunk in binaryChunks:
    hexChunks.append("%x" % int(binChunk, 2))    
  return "".join(hexChunks)

def __doDecriptionChunks(binaryMergedString):
  """Break a string of 0's and 1's in pieces of 4 chars
  @param binaryMergedString: a string of 0's and 1's to break in 4-part pieces
  @return: an array of 4 character parts of the original string"""
  binaryChunks = []
  for index in range(0, len(binaryMergedString), 4):
    binaryChunk = binaryMergedString[index:index + 4]
    binaryChunks.append(binaryChunk)
  return binaryChunks

def __doDecriptionSwaps(hash, keys):
  """Swap the first 256 indices from keys on the hash with the last 128 elements from the hash
  @param hash: the hash to do swaps on
  @param keys: the generated keys to use as indices for the swaps
  @return: hash after swaps"""
  for index in range(256, 0, -1):
    key = keys[index]
    swapTarget = index % 128
    oldHashKey = hash[key]
    hash[key] = hash[swapTarget]
    hash[swapTarget] = oldHashKey
  return hash

def __computeIndices(key1, key2):
  """Generate an array of 384 indices with values 0-127
  @param key1: first seed to generate indices from
  @param key2: second seed to generate indices from
  @return: an array of 384 indices with values between 0 and 127"""
  indices = []
  for i in range(384):
    key1 = (int(key1) * 11 + 77213) % 81371
    key2 = (int(key2) * 17 + 92717) % 192811
    indices.append((int(key1) + int(key2)) % 128)
  return indices

def __explodeBin(str1):
  # explode each char in str1 into it;s binary representation
  # and collect the result into __reg1
  __reg1 = []
  __reg3 = 0
  while (__reg3 < len(str1)):
    __reg0 = str1[__reg3]
    holder = __reg0
    if (holder == "0"):
      __reg1.append("0000")
    else:
      if (__reg0 == "1"):
        __reg1.append("0001")
      else:
        if (__reg0 == "2"): 
          __reg1.append("0010")
        else: 
          if (__reg0 == "3"):
            __reg1.append("0011")
          else: 
            if (__reg0 == "4"):
              __reg1.append("0100")
            else: 
              if (__reg0 == "5"):
                __reg1.append("0101")
              else: 
                if (__reg0 == "6"):
                  __reg1.append("0110")
                else: 
                  if (__reg0 == "7"):
                    __reg1.append("0111")
                  else: 
                    if (__reg0 == "8"):
                      __reg1.append("1000")
                    else: 
                      if (__reg0 == "9"):
                        __reg1.append("1001")
                      else: 
                        if (__reg0 == "a"):
                          __reg1.append("1010")
                        else: 
                          if (__reg0 == "b"):
                            __reg1.append("1011")
                          else: 
                            if (__reg0 == "c"):
                              __reg1.append("1100")
                            else: 
                              if (__reg0 == "d"):
                                __reg1.append("1101")
                              else: 
                                if (__reg0 == "e"):
                                  __reg1.append("1110")
                                else: 
                                  if (__reg0 == "f"):
                                    __reg1.append("1111")

    __reg3 = __reg3 + 1
  return list("".join(__reg1))

def __calculateFileHash(str1, key1, key2):
  # explode hex to bin strings, collapse to a string and return char array
  hash = __explodeBin(str1)
  # based on the keys, generate an array of 384 (256 + 128) values
  decriptIndices = __computeIndices(key1, key2)
  # from 256 to 0, swap hash[decriptIndices[x]] with hash[__reg3 % 128]
  hash = __doDecriptionSwaps(hash, decriptIndices)
  # replace the first 128 chars in hash with the formula:
  #  hash[x] = hash[x] * decriptIndices[x+256] & 1
  hash = __calcDecriptionMix(hash, decriptIndices)
  # split __reg12 in chunks of 4 chars
  chunks = __doDecriptionChunks(hash)  
  # convert each binary chunk to a hex string for the final hash
  return __toHexDecriptionString(chunks)

def SEARCH():
    keyb=xbmc.Keyboard('', 'Search FASTPASSTV')
    keyb.doModal()
    if (keyb.isConfirmed()):
        search = keyb.getText()
        print 'lagasdgasdg '+search
        if search != '':
            #encode=urllib.quote(search)
            values={'input': search,'submit': 'Search'}
            headers={ 'User-Agent' : user_agent }
            data=urllib.urlencode(values)
            req=urllib2.Request('http://www.fastpasstv.ms/search/',data,headers)
            req.add_header('User-Agent', user_agent)
            response=urllib2.urlopen(req)
            link=response.read()
            response.close()
            tvs=re.compile('<li><a href="/tv/(.+?)">(.+?)<span class="epnum">(.+?)</span></a>').findall(link)
            docs=re.compile('li><a href="/documentaries/(.+?)">(.+?)<span class="epnum">(.+?)</span></a>').findall(link)
            toon=re.compile('<li><a href="/cartoons/(.+?)">(.+?)<span class="epnum">(.+?)</span></a>').findall(link)
            mvs=re.compile('<li><a href="/movies/(.+?)">(.+?)<span class="epnum">(.+?)</span></a>').findall(link)
            for url,name,year in tvs:
                addDir(name.replace('<font class="newvid">New Episodes!</font>','(NEW EPISODE)')+' ('+year+')','http://www.fastpasstv.ms/tv/'+url,10,'')
            for url,name,year in toon:
                addDir(name.replace('<font class="newvid">New Episodes!</font>','(NEW EPISODE)')+' ('+year+')','http://www.fastpasstv.ms/cartoons/'+url,9,'')
            for url,name,year in mvs:
                addDir(name+' ('+year+')','http://www.fastpasstv.ms/movies/'+url,9,'')
            for url,name,year in docs:
                addDir(name+' ('+year+')','http://www.fastpasstv.ms/documentaries/'+url,9,'')

def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
        return param

def addDir(name,url,mode,thumbnail,plot=''):
        u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
        ok=True
        liz=xbmcgui.ListItem(name, iconImage=movIcon, thumbnailImage=thumbnail)
        liz.setInfo( type="Video", infoLabels={ "Title": name, "plot": plot} )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
        return ok

class StopDownloading(Exception): 
        def __init__(self, value): 
            self.value = value 
        def __str__(self): 
            return repr(self.value) 

def Download(url, dest): 
        dp = xbmcgui.DialogProgress() 
        dp.create('Downloading', '', name) 
        start_time = time.time() 
        try: 
            urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dp, start_time)) 
        except: 
            #delete partially downloaded file 
            while os.path.exists(dest): 
                try: 
                    print 'hello' 
                    break 
                except: 
                     pass 
            #only handle StopDownloading (from cancel), ContentTooShort (from urlretrieve), and OS (from the race condition); let other exceptions bubble 
            if sys.exc_info()[0] in (urllib.ContentTooShortError, StopDownloading, OSError): 
                return 'false' 
            else: 
                raise 
        return 'downloaded' 
         
def _pbhook(numblocks, blocksize, filesize, dp, start_time): 
        try: 
            percent = min(numblocks * blocksize * 100 / filesize, 100) 
            currently_downloaded = float(numblocks) * blocksize / (1024 * 1024) 
            kbps_speed = numblocks * blocksize / (time.time() - start_time) 
            if kbps_speed > 0: 
                eta = (filesize - numblocks * blocksize) / kbps_speed 
            else: 
                eta = 0 
            kbps_speed = kbps_speed / 1024 
            total = float(filesize) / (1024 * 1024) 
            mbs = '%.02f MB of %.02f MB' % (currently_downloaded, total) 
            e = 'Speed: %.02f Kb/s ' % kbps_speed 
            e += 'ETA: %02d:%02d' % divmod(eta, 60) 
            dp.update(percent, mbs, e) 
        except: 
            percent = 100 
            dp.update(percent) 
        if dp.iscanceled(): 
            dp.close() 
            raise StopDownloading('Stopped Downloading')

def Play(finalurl):
       	if (fpt.getSetting('download') == '0'):
                    dia = xbmcgui.Dialog()
                    ret = dia.select('Streaming Options', ['Play','Download'])
                    if (ret == 0):
			    addLink('Play',finalurl,'','','')
			    item = xbmcgui.ListItem(name)
          		    ok=xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(finalurl, item)
                    elif (ret == 1):
                            path = xbmc.translatePath(os.path.join(fpt.getSetting('download_path'), name))
                            Download(finalurl,path+name+'.flv')
                    else:
                            return
	elif (fpt.getSetting('download') == '1'):
 		addLink('Play',finalurl,'','','')
		item = xbmcgui.ListItem(name)
          	ok=xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(finalurl, item)
        elif (fpt.getSetting('download') == '2'):
                path = xbmc.translatePath(os.path.join(fpt.getSetting('download_path'), name))
                Download(finalurl,path+name+'.flv')
        else:
        	return
 
def addLink(name,url,iconimage,plot,date):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        liz.setInfo( type="Video", infoLabels={ "Title": name } )
	liz.setProperty("IsPlayable","true");
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=False)
        return ok

params=get_params()
url=None
name=None
mode=None

try:
        url=urllib.unquote_plus(params["url"])
except:
        pass
try:
        name=urllib.unquote_plus(params["name"])
except:
        pass
try:
        mode=int(params["mode"])
except:
        pass
print "Mode: "+str(mode)
print "URL: "+str(url)
print "Name: "+str(name)

if mode==None or url==None or len(url)<1:
        print "categories"
        CATS()
elif mode==1:
        print "PAGE"
        MOVALL(url,name)
elif mode==2:
        print "PAGE"
        TVALL(url,name)
elif mode==4:
        print "SEARCH  :"+url
        SEARCH()
elif mode==5:
        print "PAGE"
        VIDBUX(url,name)
elif mode==6:
        print "PAGE"
        Nova(url,name)
elif mode==8:
        print "PAGE"
        MEGA(url,name)
elif mode==9:
        print "PAGE"
        MAIN(url,name)
elif mode==10:
        print "PAGE"
        TVSHOWS(url,name)
elif mode==11:
        print "PAGE"
        LATEST(url,name)
elif mode==12:
        print "PAGE"
        PUTLOC(url,name)
elif mode==14:
        print "PAGE"
        DOCALL(url,name)
elif mode==15:
        print "PAGE"
        VIDSDIVX(url,name)
elif mode==16:
        print "PAGE"
        VIDXFLV(url,name)
elif mode==17:
        print "PAGE"
        VIDEOWEED(url,name)
elif mode==18:
        print "PAGE"
        VIDEOBB(url,name)
elif mode==19:
        print "PAGE"
        MOVSHARE(url,name)
elif mode==20:
        print "PAGE"
        FAVTV()
elif mode==21:
        print "PAGE"
        ADDFAVS(url,name)
elif mode==22:
        print "PAGE"
        REMFAVS(url,name)
elif mode==23:
        print "PAGE"
        SOCKSH(url,name)
elif mode==24:
        print "PAGE"
        DIVXSTAGE(url,name)
elif mode==25:
        print "PAGE"
        ROYAL(url,name)
elif mode==26:
        print "PAGE"
        MOTION(url,name)
elif mode==27:
        print "PAGE"
        GOOGLE(url,name)
elif mode==28:
        print "PAGE"
        VIDXFLV(url,name)
elif mode==35:
        print "PAGE"
        TVEPS(url,name)
elif mode==36:
        print "PAGE"
        MOVALPH(url,name)
elif mode==37:
        print "PAGE"
        TVALPH(url,name)
elif mode==30:
        print "PAGE"
        FAVMOV()
elif mode==31:
        print "PAGE"
        FAVS()
elif mode==32:
        print "PAGE"
        POPULAR(url)
elif mode==33:
        print "PAGE"
        RECENT()
elif mode==38:
        print "PAGE"
        TOONALL(url,name)

xbmcplugin.endOfDirectory(int(sys.argv[1]))